import { Ref, SetupContext, ref, watch } from "vue";
import { MemoryVoicePalyBarProps } from "../components/play-bar/play-bar.props";
import { PlayState, ResourceInfo, UseTextToSpeech, UtteranceSettings } from "./types";
import { highlight } from "./hight-light";

export function useTextToSpeech(
    resourceInfo: ResourceInfo,
    context: SetupContext,
    curSpeechSettings:Ref<UtteranceSettings>,
): UseTextToSpeech {
    const synth = window.speechSynthesis;
    const docs=ref(resourceInfo);
    // 当前播放那个类别
    var curState='title';
    // 播放状态
    const speechState=ref('');

    const progress=ref({curType:'title',highlightText:'',realProgress:'0',speechLength:0,totalLength:0});
    const  playContent=(newValue)=>{
        if(!newValue){
            return;
        }
        // 创建新的播放
        const utterance = new SpeechSynthesisUtterance(newValue);
        ["lang","pitch","rate",'volume'].map((key)=>{
            utterance[key]=curSpeechSettings.value[key];
        });
        // //当前播放完毕
        utterance.addEventListener('end', () => {            
            speechState.value=PlayState[curState+'End']; 
            if(curState=='title'){                                       
                curState='content';   
                // 播放内容
                playContent(docs.value[curState]);
            }
        });
        // // 开始
        utterance.addEventListener('start', (event) => {
            speechState.value=PlayState[curState+'Start'];
        });
        utterance.addEventListener('error', (event) => {
            speechState.value=PlayState.error;
        });
         // 进度
        utterance.addEventListener('boundary', (event) => {
            const { charIndex, charLength } = event;  
            let totalLength=docs.value['title'].length+docs.value['content'].length;
            let tProgress=(curState=='title'? 0:docs.value['title'].length)+charIndex+charLength;
            let highlightText=highlight(docs.value[curState],charIndex,charLength);
            progress.value={
                curType:curState,
                highlightText:highlightText,
                totalLength:totalLength,
                speechLength:tProgress,
                realProgress:(100*tProgress/totalLength).toFixed(2)
            };
        });
        // 播放
        synth.speak(utterance);
    }
    if(docs.value){       
        // 取消之前的播放
       synth.cancel();
       playContent(docs.value[curState]);
    }
    
//    // 当前资料更新 
//    watch(docs, (newValue, oldValue) => {
        //         console.log('当前资料更新');
        // // 取消所有等待播放资源
        // synth.cancel();
        // // 先播放标题
        // playContent(newValue.title);
//    });
   
   

    return {
        progress,speechState
    };
}
